package com.qlslylq.ad.sdk.core.loader;

import android.app.Activity;
import android.text.TextUtils;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsRewardVideoAd;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsVideoPlayConfig;
import com.kwad.sdk.api.SdkConfig;
import com.mbridge.msdk.out.MBRewardVideoHandler;
import com.mbridge.msdk.out.MBridgeIds;
import com.mbridge.msdk.out.RewardInfo;
import com.mbridge.msdk.out.RewardVideoListener;
import com.qlslylq.ad.sdk.config.CsjMgrHolder;
import com.qlslylq.ad.sdk.config.KsMgrHolder;
import com.qlslylq.ad.sdk.constant.AppConst;
import com.qlslylq.ad.sdk.constant.UrlConst;
import com.qlslylq.ad.sdk.core.ad.BaseAd;
import com.qlslylq.ad.sdk.core.interceptor.RewardVideoADListener;
import com.qlslylq.ad.sdk.core.interceptor.WindRewardedVideoAdListener;
import com.qlslylq.ad.sdk.core.listener.RewardAdListener;
import com.qlslylq.ad.sdk.core.mgr.PoolMgr;
import com.qlslylq.ad.sdk.core.rsp.AdError;
import com.qlslylq.ad.sdk.enums.AdEventSign;
import com.qlslylq.ad.sdk.enums.AdPlatformEnum;
import com.qlslylq.ad.sdk.enums.ErrorEnum;
import com.qlslylq.ad.sdk.enums.OsType;
import com.qlslylq.ad.sdk.model.req.UserBehaviorAddDTO;
import com.qlslylq.ad.sdk.model.rsp.AdPlaceWebConfigureVO;
import com.qlslylq.ad.sdk.net.api.ApiServiceImpl;
import com.qlslylq.ad.sdk.util.DecimalUtils;
import com.qlslylq.ad.sdk.util.GsonUtils;
import com.qlslylq.ad.sdk.util.Log;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.ServerSideVerificationOptions;
import com.sigmob.windad.WindAdError;
import com.sigmob.windad.rewardedVideo.WindRewardAdRequest;
import com.sigmob.windad.rewardedVideo.WindRewardInfo;
import com.sigmob.windad.rewardedVideo.WindRewardedVideoAd;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qlslylq.ad.sdk.enums.OrientationEnum.LANDSCAPE;
import static com.qlslylq.ad.sdk.enums.OrientationEnum.PORTRAIT;

/**
 * 激励广告加载器<br/>
 */
public class RewardAdLoader extends AdLoader<RewardAdListener> {

    //服务端奖励-透传消息所需
    private String userId;

    //服务端奖励-透传消息所需
    private Map<String, String> extraData = new HashMap<>();

    public RewardAdLoader(Activity context, long posId, RewardAdListener adListener) {
        super(context, posId, adListener);
    }

    /**
     * 加载并展示<br/>
     */
    protected void load(AdPlaceWebConfigureVO config) {
        AdPlatformEnum platform = config.getPlatform();
        String posId = config.getPositionId();

        if (extraData != null) {
            extraData.put("userId", userId);
            extraData.put("posId", posId);
            extraData.put("platform", platform.getName());
            extraData.put("osType", OsType.Android.getName());
        }

        if (platform == AdPlatformEnum.PLATFORM_CSJ) {//穿山甲
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(posId)
                    .setUserID(userId)
                    .setMediaExtra(GsonUtils.gsonString(extraData))
                    .setOrientation(orientation == PORTRAIT ? TTAdConstant.VERTICAL : TTAdConstant.HORIZONTAL)//方向由创建时决定，且不能改变，此处应可省
                    .setExpressViewAcceptedSize(AppConst.CSJ_VIDEO_SIZE, AppConst.CSJ_VIDEO_SIZE)//只要设置的值大于0即可
                    .setAdLoadType(TTAdLoadType.PRELOAD)//[实时加载，预加载]
                    .build();
            CsjMgrHolder.createAdNative(context).loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
                @Deprecated
                public void onRewardVideoCached() {

                }

                public void onRewardVideoCached(TTRewardVideoAd ad) {

                }

                public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                    PoolMgr.getInstance().push(ad, config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, RewardAdLoader.super.posId));
                }

                public void onError(int code, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, code, msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, RewardAdLoader.super.posId));
                }
            });

        } else if (platform == AdPlatformEnum.PLATFORM_YLH) {//优量汇
            PoolMgr.getInstance().push(new Object(), config);
        } else if (platform == AdPlatformEnum.PLATFORM_KS) {//快手联盟
            Map<String, String> rewardCallbackExtraData = new HashMap<>();
            rewardCallbackExtraData.put(AppConst.KEY_USERID_KS, userId);
            rewardCallbackExtraData.put(AppConst.KEY_EXTRA_KS, GsonUtils.gsonString(extraData));

            KsScene scene = new KsScene.Builder(DecimalUtils.parseLongSafe(posId))
                    .setBackUrl(UrlConst.BACK_URL_AD) // scheme逆向唤醒协议名设置，与清单中所注册的协议名保持一致即可
                    .screenOrientation(orientation == PORTRAIT ? SdkConfig.SCREEN_ORIENTATION_PORTRAIT : SdkConfig.SCREEN_ORIENTATION_LANDSCAPE)//不起决定性
                    .rewardCallbackExtraData(rewardCallbackExtraData)
                    .build();
            KsMgrHolder.get().loadRewardVideoAd(scene, new KsLoadManager.RewardVideoAdListener() {
                public void onRewardVideoAdLoad(List<KsRewardVideoAd> list) {
                    try {
                        KsRewardVideoAd ad = list.get(0);

                        PoolMgr.getInstance().push(ad, config);

                        getAdListener().onAdLoad();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NO_AD.rsp(platform, adType)));
                        getAdListener().onAdLoadError(ErrorEnum.ERR_NO_AD.rsp(platform, adType));
                    }

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, RewardAdLoader.super.posId));
                }

                public void onRequestResult(int adNumber) {

                }

                public void onError(int code, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, code, msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, RewardAdLoader.super.posId));
                }
            });
        } else if (platform == AdPlatformEnum.PLATFORM_SIGMOB) {
            WindRewardAdRequest request = new WindRewardAdRequest(posId, null, null);
            request.setUserId(userId);
            if (extraData != null) {
                request.setOptions(new HashMap<>(extraData));
            }
            WindRewardedVideoAdListener listener = new WindRewardedVideoAdListener() {
                public void onVideoAdPreLoadSuccess(String placementId) {

                }

                public void onVideoAdPreLoadFail(String placementId) {

                }

                public void onVideoAdLoadSuccess(String placementId) {
                    PoolMgr.getInstance().push(getAd(), config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, RewardAdLoader.super.posId));
                }

                public void onVideoAdPlayStart(String placementId) {
                    onAdShowSafety();
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, RewardAdLoader.super.posId));
                }

                public void onVideoAdPlayEnd(String placementId) {
                    getAdListener().onAdComplete();
                }

                public void onVideoAdClicked(String placementId) {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, RewardAdLoader.super.posId));
                }

                public void onVideoAdClosed(WindRewardInfo windRewardInfo, String placementId) {
                    if (windRewardInfo.isComplete()) {
                        getAdListener().onReward();
                    }
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, RewardAdLoader.super.posId));
                }

                public void onVideoAdLoadError(WindAdError error, String placementId) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getMessage())));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, error.getErrorCode(), error.getMessage()));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, RewardAdLoader.super.posId));
                }

                public void onVideoAdPlayError(WindAdError error, String placementId) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getMessage())));
                    onAdShowErrorSafety(AdError.build(platform, adType, error.getErrorCode(), error.getMessage()), platform, false);
                }
            };
            WindRewardedVideoAd ad = new WindRewardedVideoAd(context, request);
            listener.setAd(ad);
            ad.setWindRewardedVideoAdListener(listener);
            ad.loadAd();
        } else if (platform == AdPlatformEnum.PLATFORM_MINTEGRAL) {
            MBRewardVideoHandler ad = new MBRewardVideoHandler(context, null, posId);
            ad.setRewardVideoListener(new RewardVideoListener() {
                public void onLoadSuccess(MBridgeIds ids) {

                }

                public void onVideoLoadSuccess(MBridgeIds ids) {
                    PoolMgr.getInstance().push(ad, config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, RewardAdLoader.super.posId));
                }

                public void onVideoLoadFail(MBridgeIds ids, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, ErrorEnum.ERR_LOAD_FAILD.getId(), msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, ErrorEnum.ERR_LOAD_FAILD.getId(), msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, RewardAdLoader.super.posId));
                }

                public void onShowFail(MBridgeIds ids, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, ErrorEnum.ERR_SHOW_FAILD.getId(), msg)));
                    onAdShowErrorSafety(AdError.build(platform, adType, ErrorEnum.ERR_SHOW_FAILD.getId(), msg), platform, false);
                }

                public void onAdShow(MBridgeIds ids) {
                    onAdShowSafety();
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, RewardAdLoader.super.posId));
                }

                public void onAdClose(MBridgeIds ids, RewardInfo rewardInfo) {
                    if (rewardInfo.isCompleteView()) {
                        getAdListener().onReward();
                    }
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, RewardAdLoader.super.posId));
                }

                public void onVideoAdClicked(MBridgeIds ids) {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, RewardAdLoader.super.posId));
                }

                public void onVideoComplete(MBridgeIds ids) {
                    getAdListener().onAdComplete();
                }

                public void onEndcardShow(MBridgeIds ids) {
                }
            });
            ad.load();
        }
    }

    protected void show(BaseAd ad) {
        AdPlaceWebConfigureVO config = ad.getConfig();
        AdPlatformEnum platform = config.getPlatform();
        String posId = config.getPositionId();

        if (extraData != null) {
            extraData.put("userId", userId);
            extraData.put("posId", posId);
            extraData.put("platform", platform.getName());
            extraData.put("osType", OsType.Android.getName());
        }

        if (platform == AdPlatformEnum.PLATFORM_CSJ) {//穿山甲
            TTRewardVideoAd adThird = (TTRewardVideoAd) ad.getAd();
            adThird.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                public void onAdShow() {
                    onAdShowSafety();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, RewardAdLoader.super.posId));
                }

                public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
                    getAdListener().onReward();
                }

                public void onVideoComplete() {
                    getAdListener().onAdComplete();
                }

                public void onAdClose() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, RewardAdLoader.super.posId));
                }

                public void onSkippedVideo() {

                }

                public void onAdVideoBarClick() {//广告下载bar点击
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, RewardAdLoader.super.posId));
                }

                public void onVideoError() {
                    Log.e(GsonUtils.gsonString(ErrorEnum.ERR_VIDEO_PLAY.rsp(platform, adType)));
                    onAdShowErrorSafety(ErrorEnum.ERR_VIDEO_PLAY.rsp(platform, adType), platform, false);
                }
            });

            adThird.showRewardVideoAd(context, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, null);
        } else if (platform == AdPlatformEnum.PLATFORM_YLH) {//优量汇
            RewardVideoADListener listener = new RewardVideoADListener() {
                private boolean hasPop = false;

                public void onVideoCached() {

                }

                public void onADLoad() {
//                    getAd().showAD(context);
                    getAd().showAD();
                    getAdListener().onAdLoad();
                    hasPop = true;

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, RewardAdLoader.super.posId));
                }

                public void onADShow() {
                    onAdShowSafety();
                }

                public void onADExpose() {
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, RewardAdLoader.super.posId));
                }

                public void onReward(Map<String, Object> map) {
                    getAdListener().onReward();
                }

                public void onVideoComplete() {
                    getAdListener().onAdComplete();
                }

                public void onADClose() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, RewardAdLoader.super.posId));
                }

                public void onADClick() {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, RewardAdLoader.super.posId));
                }

                public void onError(com.qq.e.comm.util.AdError error) {//加载错误或播放错误
                    Log.e(GsonUtils.gsonString(error));
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg())));
                    if (!hasPop) {
                        getAdListener().onAdLoadError(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg()));
                    } else {
                        onAdShowErrorSafety(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg()), platform, false);
                    }

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, RewardAdLoader.super.posId));
                }
            };
            RewardVideoAD adYlh = new RewardVideoAD(context, posId, listener, true);
            listener.setAd(adYlh);
            if (!TextUtils.isEmpty(userId)) {
                ServerSideVerificationOptions options = new ServerSideVerificationOptions.Builder()
                        .setUserId(userId)
                        .setCustomData(GsonUtils.gsonString(extraData))
                        .build();
                adYlh.setServerSideVerificationOptions(options);
            }
            adYlh.loadAD();
        } else if (platform == AdPlatformEnum.PLATFORM_KS) {//快手联盟
            KsRewardVideoAd adThird = (KsRewardVideoAd) ad.getAd();
            KsVideoPlayConfig videoPlayConfig = new KsVideoPlayConfig.Builder()
                    .showLandscape(orientation == LANDSCAPE)//方向
                    .videoSoundEnable(true)//声音策略
                    .build();
            adThird.setRewardAdInteractionListener(new KsRewardVideoAd.RewardAdInteractionListener() {
                public void onVideoPlayStart() {
                    onAdShowSafety();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, RewardAdLoader.super.posId));
                }

                public void onRewardVerify() {
                    getAdListener().onReward();
                }

                public void onRewardStepVerify(int i, int i1) {

                }

                public void onVideoPlayEnd() {
                    getAdListener().onAdComplete();
                }

                public void onPageDismiss() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, RewardAdLoader.super.posId));
                }

                public void onVideoSkipToEnd(long l) {

                }

                public void onAdClicked() {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, RewardAdLoader.super.posId));
                }

                public void onVideoPlayError(int code, int extra) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, String.valueOf(extra))));
                    onAdShowErrorSafety(AdError.build(platform, adType, code, String.valueOf(extra)), platform, false);
                }
            });
            adThird.showRewardVideoAd(context, videoPlayConfig);
        } else if (platform == AdPlatformEnum.PLATFORM_SIGMOB) {
            WindRewardedVideoAd adThird = (WindRewardedVideoAd) ad.getAd();
            if (adThird.isReady()) {
                adThird.show(context, null);
            } else {
                Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NOT_READY.rsp(platform, adType)));
                onAdShowErrorSafety(ErrorEnum.ERR_NOT_READY.rsp(platform, adType), platform, true);
            }
        } else if (platform == AdPlatformEnum.PLATFORM_MINTEGRAL) {
            MBRewardVideoHandler adThird = (MBRewardVideoHandler) ad.getAd();
            if (adThird.isReady()) {
                adThird.show(userId, GsonUtils.gsonString(extraData));
            } else {
                Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NOT_READY.rsp(platform, adType)));
                onAdShowErrorSafety(ErrorEnum.ERR_NOT_READY.rsp(platform, adType), platform, true);
            }
        }
    }

    /**
     * 服务端奖励-透传消息所需<br/>
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * 服务端奖励-透传消息所需<br/>
     */
    public void setExtraData(Map<String, String> extraData) {
        this.extraData = extraData;
        if (this.extraData == null) {
            this.extraData = new HashMap<>();
        }
    }
}
